<?php
/**
 * 产品Model类
 * @file 	ItemsModel.class.php
 * @author 	kelecode@gmail.com
 * @date 	2013-06-13
 * modify       
 */
class ItemsModel extends Model{
	
	private $table;
	private $categoriesTable;
	
	public function __construct(){
		parent::__construct();
		
		$this->table = C('db_table_prefix').'items';		
		$this->categoriesTable = C('db_table_prefix').'items_categories';
	}
	
	/**
	 * 获取全部或单条列表数据
	 * @param 	int $cid 
	 * @return 	array $itemsList
	 */
	public function itemList($order='ctime',$cid=null,$pageSize=27){
		$order = !in_array($order,array('ctime','sort')) ? 'ctime' : $order;
		$cid = (int)$cid;
		$limit = (int)$limit;
		$p = (int)getgpc('p');
		$p = $p <= 0 ? 1 : $p;
		$itemList = array();
		$sqlCount = "SELECT COUNT(*) AS `num` FROM `{$this->table}` WHERE `status`=1";
		if( !empty($cid) ){
			$sqlCount .= " AND `cid`='{$cid}'";
		}
		$count = $this->query($sqlCount);
		$sql = "SELECT `id`,`cid`,`name`,`price`,`url`,`image`,`description`,`ctime` FROM `{$this->table}` WHERE `status`=1";
		if( !empty($cid) ){
			$sql .= " AND `cid`='{$cid}'";
		}
		$offset = ($p-1) * $pageSize;
		if($order == 'ctime'){
			$sql .= " ORDER BY `ctime` DESC";
		}else{
			$sql .= " ORDER BY `sort` ASC";
		}
		$sql .= " ,`id` DESC LIMIT {$offset},{$pageSize}";
		$itemList = $this->query($sql);
		
		return array('count' => $count[0]['num'], 'lists' => $itemList);
	}
	
	public function getItemsById($id){
		$items = $this->query("SELECT * FROM `{$this->table}` WHERE `id`='{$id}'");

		return $items[0];
	}
	
	public function categoryList(){
		$lists = $this->query("SELECT `id`,`name` AS `cname` FROM `{$this->categoriesTable}` WHERE `status`=1");
		$categoryList = array();
		foreach($lists as $list){
			$categoryList[$list['id']] = $list['cname'];
		}
		
		return $categoryList;
	}
	
}